using CacheHelper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using XKPlatform.Common.Const;
using XKPlatform.Common.Extends;
using XKPlatform.DataModels;
using XKPlatform.Common;
using XKPlatform.IService;
using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using XKPlatform.DataModels.Model;
using Microsoft.AspNetCore.Http;
using XKPlatform.DataModels.SysModel;
using XKPlatform.Common.Enums;

namespace XKPlatform.Controllers
{
    public class AccountController : Controller
    {
        //private Itest11Service _itest11;
        private readonly ICache _cache;
        //private readonly ITestService _testService;
        //private readonly ISysFlowStateService _flow;
        private readonly IHttpContextAccessor _IHttpContextAccessor;
       

        // ITestService testService, ISysFlowStateService flow,
        public AccountController(ICache cache)
        {
            // _IHttpContextAccessor = httpContextAccessor;
            //_itest11 = itest;
            _cache = cache;
            //_testService = testService;
            //_flow = flow;
         
        }
        private static SysUser usernow;
        #region 判断是否登陆
        [AllowAnonymous]
        public JsonResult IsLogin()
        {
            return Json(new { code = SSOClient.IsLogin ? 0 : 0 });
        }
        #endregion

        #region 管理后台登陆
        [AllowAnonymous]
        [HttpPost]
        public async Task<JsonResult> Login(string loginAccount, string loginPassword)
        { 
            if (!SSOClient.Validate(loginAccount, loginPassword, out SysUser user))
                return Json(new { code = 1, msg = "帐号或密码不正确，请重新输入！" });



            usernow = user;
            user.Password = "";
            string token = SSOClient.GetAccessToken(user.UserID.ToString(), user.UserName, user);

            if (user.LastLoginTime == null)
            {
                return Json(new
                {
                    code = 0,
                    data = new
                    {
                        user.UserNo,
                        user.Email,
                        FirstLogin = true,
                        access_token = token,
                        UserName = user.UserName
                        //expires_at = new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds()//new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                    }
                });
            }

            //var ds = GetProInfo(user.DefaultRoleID.ToString().ToUpper());
            //if (ds == null && ds.Tables[0].Rows.Count == 0)
            //    return Json(new
            //    {
            //        code = -1

            //    });
            //List<LoginProject> project = new List<LoginProject>();

            //for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            //{
            //    LoginProject LP = new LoginProject();
            //    LP.projectno = ds.Tables[0].Rows[i]["ProjectNo"].ToString();
            //    LP.projectname = ds.Tables[0].Rows[i]["ProjectName"].ToString();
            //    LP.projecturl = ds.Tables[0].Rows[i]["proUrl"].ToString();
            //    project.Add(LP);
            //}


            return Json(new
            {
                code = 0,
                data = new
                {
                    access_token = token,
                    // project,
                    // UserNo= user.UserNo,
                    Email = user.Email,
                    UserName = user.UserName
                    //expires_at = new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds()//new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                }
            });

        }

        [HttpPost]
        public JsonResult SaveProject(string proid)
        {

            //string sql = string.Format("select top 1 No from SysProject where ProjectNo='{0}'", proid);
            //DataSet ds = SqlHelper.Query(sql);
            //if (ds.Tables[0].Rows.Count > 0)
            //{
            //    //userInfo.project = ds.Tables[0].Rows[0]["No"].ToString();
            //    TimeSpan timeSpan = TimeSpan.FromHours(GlobleConst.expTime);
            //    var context = _IHttpContextAccessor.HttpContext;
            //    var request = context.Request;
            //    //Console.WriteLine("path:" + request.Path);
            //    var token = request.Headers["Authorization"];//获取token
            //    string[] tokenlist = token.ToString().Split(' ');
            //    if (tokenlist.Length < 2)
            //    {
            //        return Json(new { code = -1 });
            //    }
            //    string getUserAccessTokenByUserInfoKey = RedisKeyConst.UserAccesstokenByUserInfo;
            //dynamic userdata = new
            //{
            //    userInfo.UserID,
            //    userInfo.UserNo,
            //    userInfo.UserName,
            //    userInfo.Org,
            //    DefaultRoleID = userInfo.Roles,
            //    project = ds.Tables[0].Rows[0]["No"].ToString(),
            //    IsAdmin = userInfo.IsAdmin,
            //    IsDev = userInfo.IsDev,


            //};
            //var sysUser = userInfo;
            //sysUser.project = ds.Tables[0].Rows[0][0].ToString();
            //string UserInfo = JsonConvert.SerializeObject(sysUser);

            //_cache.Set(getUserAccessTokenByUserInfoKey + tokenlist[1], UserInfo, timeSpan);
            return Json(new { code = 0 });
            //}
            //return Json(new { code = -1 });
        }
        #endregion

        #region 获取项目信息
        [AllowAnonymous]
        [HttpPost]
        public JsonResult GetPro()
        {

            var userInfo = SSOClient.getUser(HttpContext);
            QuerySuite querySuite = new QuerySuite("SysProject a left join SysProjectRole b on b.ProjectID=a.No where ProjectName is not null and a.RecordStatus=0", "distinct (ProjectName) as ProjectName,ProjectNo,proUrl");
            querySuite.AddParam("RoleID", "=", userInfo.DefaultRoleID.ToString());

            DataSet ds = SqlHelper.Query(querySuite.SelectSql, querySuite.Params);
            if (ds == null && ds.Tables[0].Rows.Count == 0)
                return Json(new
                {
                    code = -1

                });
            List<LoginProject> project = new List<LoginProject>();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                LoginProject LP = new LoginProject();
                LP.projectno = ds.Tables[0].Rows[i]["ProjectNo"].ToString();
                LP.projectname = ds.Tables[0].Rows[i]["ProjectName"].ToString();
                LP.projecturl = ds.Tables[0].Rows[i]["proUrl"].ToString();
                project.Add(LP);
            }

            return Json(new
            {
                code = 0,
                data = new
                {
                    project
                }

            });

        }
        #endregion

        private DataSet GetProInfo(string roles)
        {
            QuerySuite querySuite = new QuerySuite("SysProject a left join SysProjectRole b on b.ProjectID=a.No where ProjectName is not null and a.RecordStatus=0", "distinct (ProjectName) as ProjectName,ProjectNo,proUrl", "ProjectNo");
            if (roles != HttpContextCore.developID)
            {
                querySuite.AddParam("RoleID", "=", roles);
            }

            DataSet ds = SqlHelper.Query(querySuite.SelectSql, querySuite.Params);
            return ds;
        }


        #region 获取用户信息
        public JsonResult GetUser()
        {

            Console.WriteLine("=======获取用户信息=======");
            var userInfo = SSOClient.getUser(HttpContext);
            if (userInfo == null)
                return Json(new
                {
                    code = 0

                });
            //QuerySuite querySuite = new QuerySuite("SysProject a left join SysProjectRole b on b.ProjectID=a.No where ProjectName is not null", "distinct (ProjectName) as ProjectName,ProjectNo,proUrl", "ProjectNo");
            //if (userInfo.Roles.ToUpper() != "EBF7BF27-3892-4F6D-899E-A484FAAAF2B4")
            //{
            //    querySuite.AddParam("RoleID", "=", userInfo.Roles);
            //}

            //DataSet ds = SqlHelper.Query(querySuite.SelectSql, querySuite.Params);
            //var ds = GetProInfo(userInfo.DefaultRoleID.ToString().ToUpper());
            //if (ds == null || ds.Tables[0].Rows.Count == 0)
            //    return Json(new
            //    {
            //        code = -1

            //    });
            //List<LoginProject> project = new List<LoginProject>();
            //if (proId.IsNullOrEmpty())
            //{
            //    proId = ds.Tables[0].Rows[0]["ProjectNo"].ToString();
            //}
            //DataRow[] dr = ds.Tables[0].Select("ProjectNo='" + proId + "'");
            //if (dr.Length > 0)
            //{
            //    LoginProject LP = new LoginProject();
            //    LP.projectno = dr[0]["ProjectNo"].ToString();
            //    LP.projectname = dr[0]["ProjectName"].ToString();
            //    LP.projecturl = dr[0]["proUrl"].ToString();
            //    project.Add(LP);
            //}
            //for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            //{
            //    if (ds.Tables[0].Rows[i]["ProjectNo"].ToString() != proId)
            //    {
            //        LoginProject LP = new LoginProject();
            //        LP.projectno = ds.Tables[0].Rows[i]["ProjectNo"].ToString();
            //        LP.projectname = ds.Tables[0].Rows[i]["ProjectName"].ToString();
            //        LP.projecturl = ds.Tables[0].Rows[i]["proUrl"].ToString();
            //        project.Add(LP);
            //    }
            //}
            return Json(new
            {
                code = 0,
                data = new
                {
                    userInfo.UserNo,
                    userInfo.UserName,
                    userInfo.UserName_EN,
                    userInfo.Mobile,
                    userInfo.Email,
                    userInfo.DepartmentID

                }

            });

        }
        #endregion

        #region 获取菜单
        public JsonResult GetMenu()
        {
            var userInfo = SSOClient.getUser(HttpContext);
            string proId = "001";
            QuerySuite querySuite = new QuerySuite("SysPage a,SysRolePage b,SysProjectPage c where a.PageID=b.PageID and a.PageID=c.PageID and proID=@proID", " distinct a.PageID,ParentID,PageName,PageName_EN,PageIcon,TemplateUrl,PageUrl,Sign,AreaCols,AreaType,ActionUrl,PageType,OrderNo,IsHide", "OrderNo");
            querySuite.AddParam("proID", proId);
            querySuite.AddParam("RoleID", "inid", userInfo.DefaultRoleID.ToString());
            querySuite.AddParam("OS", "=", "factory");
            querySuite.AddParam("ParentID", "isnotnull");

            DataTable dtRs = new DataTable();
            DataSet ds = SqlHelper.Query(querySuite.SelectSql, querySuite.Params);

            QuerySuite querySuite3 = new QuerySuite("SysPage a,SysUserPage b,SysProjectPage c where a.PageID=b.PageID and a.PageID=c.PageID and proID=@proID", " distinct a.PageID,ParentID,PageName,PageName_EN,PageIcon,TemplateUrl,PageUrl,Sign,AreaCols,AreaType,ActionUrl,PageType,OrderNo,IsHide", "OrderNo");
            querySuite3.AddParam("proID", proId);
            querySuite3.AddParam("UserID", "inid", userInfo.UserID.ToString());
            querySuite3.AddParam("OS", "=", "factory");
            querySuite3.AddParam("ParentID", "isnotnull");

            DataSet ds3 = SqlHelper.Query(querySuite3.SelectSql, querySuite3.Params);

            ds.Merge(ds3);

            if (userInfo.DefaultRoleID.ToString().ToUpper() == HttpContextCore.developID)
            {
                QuerySuite querySuite2 = new QuerySuite("SysPage where PageID in ('66601A83-E7B9-4BDF-83F0-4FF4F8D1FD92','9065FA98-473C-4E78-A8C8-CF2CEB71E905','E58332B0-DCE8-445F-B82B-E77AF93B80F9') or " +
" ParentID in ('9065FA98-473C-4E78-A8C8-CF2CEB71E905', 'E58332B0-DCE8-445F-B82B-E77AF93B80F9') or ParentID in (select PageID from SysPage" +
" where ParentID in ('9065FA98-473C-4E78-A8C8-CF2CEB71E905', 'E58332B0-DCE8-445F-B82B-E77AF93B80F9')) or ParentID in(select PageID from SysPage" +
" where ParentID in (select PageID from SysPage where ParentID in ('9065FA98-473C-4E78-A8C8-CF2CEB71E905', 'E58332B0-DCE8-445F-B82B-E77AF93B80F9')))", " distinct PageID,ParentID,PageName,PageName_EN,PageIcon,TemplateUrl,PageUrl,Sign,AreaCols,AreaType,ActionUrl,PageType,OrderNo,IsHide", "OrderNo");
                DataSet ds2 = SqlHelper.Query(querySuite2.SelectSql, querySuite2.Params);
                ds.Merge(ds2);
                DataView dv = new DataView(ds.Tables[0]);
                dtRs = dv.ToTable(true, new[] { "PageID", "ParentID", "PageName", "PageName_EN", "PageIcon", "TemplateUrl", "PageUrl", "Sign", "AreaCols", "AreaType", "ActionUrl", "PageType", "OrderNo", "IsHide" });
            }
            else
            {
                //dtRs = ds.Tables[0];

                DataView dv = new DataView(ds.Tables[0]);
                dtRs = dv.ToTable(true, new[] { "PageID", "ParentID", "PageName", "PageName_EN", "PageIcon", "TemplateUrl", "PageUrl", "Sign", "AreaCols", "AreaType", "ActionUrl", "PageType", "OrderNo", "IsHide" });
            }

            return Json(new { code = 0, data = QuerySuite.ToDictionary(dtRs) });


        }
        #endregion
        #region 获取首页
        [HttpPost]
        public JsonResult GetFirstIndex(string proId)
        {
            var userInfo = SSOClient.getUser(HttpContext);
            QuerySuite querySuite1 = new QuerySuite("SysProject a left join SysProjectRole b on b.ProjectID=a.No where ProjectName is not null", "top 1 HomePage", "ProjectNo");
            querySuite1.AddParam("RoleID", "=", userInfo.DefaultRoleID.ToString());
            //LogHelper.SaveOperateLog("Roles:" + userInfo.DefaultRoleID.ToString() + "|proId:" + proId);
            if (proId.IsNotNullOrEmpty())
            {
                querySuite1.AddParam("ProjectNo", "=", proId);
            }
            DataSet ds1 = SqlHelper.Query(querySuite1.SelectSql, querySuite1.Params);
            string project = "";

            if (ds1.Tables[0].Rows.Count > 0)
            {
                project = ds1.Tables[0].Rows[0]["HomePage"].ToString();

            }
            //LogHelper.SaveOperateLog("GetFirstIndex:" + project);
            return Json(new { code = 0, data = project });

        }
        #endregion
        #region 登出
        [AllowAnonymous]
        public JsonResult SignOut()
        {
            try
            {
                //退出操作 用户下线
                var userId = SSOClient.getUser(HttpContext).UserID.ToString();

            }
            catch (Exception ex)
            {

            }

            SSOClient.SignOut(HttpContext);
            return Json(new { code = 0 });
        }
        #endregion
    }
}